package com.cn.wanxi.servlet.product;

import com.alibaba.fastjson.JSONObject;
import com.cn.wanxi.model.ProductModel;
import com.cn.wanxi.service.IProductService;
import com.cn.wanxi.service.impl.ProductServiceImpl;
import com.cn.wanxi.util.MyImgLoad;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.util.Iterator;
import java.util.List;
import java.util.UUID;

@WebServlet("/back/product/add")
public class ProductAddServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //设置编码为utf-8
        req.setCharacterEncoding("utf-8");
        resp.setCharacterEncoding("utf-8");
        resp.setContentType("text/html;charset=utf-8");
        MyImgLoad.load(req);

        ProductModel productModel = new ProductModel();
        productModel.setName((String) req.getAttribute("productName"));
        String cuisineIdString = (String) req.getAttribute("cuisineId");
        productModel.setCuisineId(cuisineIdString == null || "".equals(cuisineIdString) ? 0 : Integer.parseInt(cuisineIdString));
        productModel.setMarketPrice(Float.parseFloat((String) req.getAttribute("marketPrice")));
        productModel.setNormalPrice(Double.parseDouble((String) req.getAttribute("normalPrice")));
        productModel.setImgHref((String) req.getAttribute("imgHref"));
        productModel.setContent((String) req.getAttribute("content"));
        String isShow = (String) req.getAttribute("isShow");
        productModel.setShow(isShow != null && !"".equals(isShow) && !"0".equals(isShow));
        String isRecomend = (String) req.getAttribute("isRecomend");
        productModel.setRecomend(isRecomend != null && !"".equals(isRecomend) && !"0".equals(isRecomend));


        IProductService iProductService = new ProductServiceImpl();
        int result = iProductService.add(productModel);

        JSONObject jsonObject = new JSONObject();
        jsonObject.put("result", result);
        resp.getWriter().println(jsonObject);
    }

    /**
     * 1.前台html  css
     * 2.js   拿到数据   Ajax里面需要数据 data
     * 3.servlet  六步
     * 4.service
     * 5.dao
     * 6.jdbc
     *
     * 产品：新增，先查询菜系
     * save   图片  js  FormData
     * 需要两个jar包
     * ajax里面需要添加两行代码
     *         processData: false,
     *         contentType: false,
     * servlet里面的代码
     */
}

